//
//  SearchListViewController.m
//  JunZeWristband
//
//  Created by Kendama on 2017/8/26.
//  Copyright © 2017年 DT. All rights reserved.
//

#import "SearchListViewController.h"
#import "SearchTableViewCell.h"
#import "AddDeviceViewController.h"
#import "SearchDeviceView.h"
#import "SearchFailView.h"
#import "BindDeviceApi.h"

@interface SearchListViewController ()<UITableViewDelegate,UITableViewDataSource>
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic,strong) NSMutableArray *dataSource;
/** 空数据提示 */
//@property (nonatomic,strong) UILabel *emptyLabel;
//@property (nonatomic,strong) UIImageView *emptyImageView;
/** 搜索设备页 **/
@property(nonatomic,strong) SearchDeviceView *searchView;
@property(nonatomic,strong) SearchFailView *failView;

@end

@implementation SearchListViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, 2.0 * NSEC_PER_SEC);
    dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
        [self updateList];
    });
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    
}

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)refreshBaseControlValue
{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateList) name:SearchDeviceList object:nil];
    [self didClickAgainSearchButton];
}

#pragma mark - 点击事件
//- (void)onRightButtonClick:(id)sender
//{
//    AddDeviceViewController *vc = [[AddDeviceViewController alloc] init];
//    [self.navigationController pushViewController:vc animated:YES];
//}

- (void)didClickAgainSearchButton
{
    [self.view bringSubviewToFront:self.searchView];
    [[DTCBluetoothManager shareInstance] scanAroundDevice];//自主控制设备扫描操作
    
}

#pragma mark - 事件处理
- (void)updateList
{
    [self.dataSource removeAllObjects];
    [self.dataSource addObjectsFromArray:[DTCBluetoothManager shareInstance].scanDeviceList];
    if (self.dataSource.count > 0)
    {
        [self.view bringSubviewToFront:self.tableView];
        [self.tableView reloadData];
    }
    else
    {
        [self.view bringSubviewToFront:self.failView];
    }
}

- (void)bindDeviceWithModel:(DTCDeviceModel *)model
{
    BindDeviceApi *api = [[BindDeviceApi alloc] initWithDic:@{@"device_mac":model.mac,@"name":model.localName,@"type":@"1"}];
    [api dtDefaultInterceptStartYTKRequestCompletionBlockWithSuccess:^(YTKBaseRequest * _Nonnull request) {
        NSDictionary *dict = [request responseJSONObject];
        if ([dict[@"errcode"] intValue] == 0)
        {
            [SVProgressHUD showSuccessWithStatus:MyNSLocalizedString(@"绑定成功")];
            [self.navigationController popViewControllerAnimated:YES];
        }
        else if ([dict[@"errcode"] intValue] == 400010)
        {
            [SVProgressHUD showErrorWithStatus:MyNSLocalizedString(@"设备已绑定")];
        }
    } failure:^(YTKBaseRequest * _Nonnull request) {
        [SVProgressHUD showErrorWithStatus:MyNSLocalizedString(@"设备已绑定")];
    }];
}

#pragma mark - 代理
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
//    return 3;
    return self.dataSource.count;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}



- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return px1920Height(200);
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return CGFLOAT_MIN;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return CGFLOAT_MIN;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    SearchTableViewCell *cell = [SearchTableViewCell dequeueReusableWithTableView:tableView];
    DTCDeviceModel *model = self.dataSource[indexPath.row];
    cell.nameLabel.text = model.localName;
    cell.bindButton.selected = YES;
    __weak typeof(self) weakSelf = self;
    cell.bindDeviceBlcok = ^{
        [weakSelf bindDeviceWithModel:model];
    };
    return cell;
}

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{
    
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    //    NewsModel *news = self.dataSource[indexPath.section];
    //    if (news.url != nil) {
    //        NSString *shopLink = news.url;
    //        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:shopLink]];
    //    }
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
}



#pragma mark - 通知处理

#pragma mark - 初始化
- (void)setNavigationStyle
{
    [self setNavigationBarTitle:MyNSLocalizedString(@"设备列表")];
//    [self setRightButtonImage:[UIImage imageNamed:@"nav_icon_add"]];
}

#pragma mark -- 懒加载
- (UITableView *)tableView
{
    if(!_tableView)
    {
        UIView *superView = self.view;
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, 0, 0) style:UITableViewStyleGrouped];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        //        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
//        MJRefreshStateHeader *header = [MJRefreshStateHeader headerWithRefreshingTarget:self refreshingAction:@selector(getDeviceList)];
//        [header setTitle:MyNSLocalizedString(@"正在刷新...") forState:MJRefreshStateRefreshing];
//        [header setTitle:MyNSLocalizedString(@"正在刷新...") forState:MJRefreshStatePulling];
//        [header setTitle:MyNSLocalizedString(@"正在刷新...") forState:MJRefreshStateWillRefresh];
//        [header setTitle:MyNSLocalizedString(@"正在刷新...") forState:MJRefreshStateIdle];
//        header.lastUpdatedTimeLabel.hidden = YES;
//        _tableView.mj_header = header;
        [superView addSubview:_tableView];
    }
    return _tableView;
}


- (NSMutableArray *)dataSource{
    if (!_dataSource) {
        _dataSource = [NSMutableArray array];
    }
    return _dataSource;
}

- (SearchDeviceView *)searchView
{
    if(!_searchView)
    {
        UIView *superView = self.view;
        _searchView = [[SearchDeviceView alloc]init];
        [superView addSubview:_searchView];
    }
    return _searchView;
}

- (SearchFailView *)failView
{
    if(!_failView)
    {
        UIView *superView = self.view;
        _failView = [[SearchFailView alloc]init];
        [superView addSubview:_failView];
        [_failView.searchButton addTarget:self action:@selector(didClickAgainSearchButton) forControlEvents:UIControlEventTouchUpInside];
    }
    return _failView;
}

//- (UILabel *)emptyLabel{
//    
//    if (!_emptyLabel) {
//        _emptyLabel = [[UILabel alloc]init];
//        _emptyLabel.text = @"还木有设备，快去添加吧！";
//        _emptyLabel.font = [UIFont systemFontOfSize:15];
//        _emptyLabel.textAlignment = NSTextAlignmentCenter;
//        _emptyLabel.textColor = [UIColor colorWithHexString:@"6F6F6F"];
//        [self.view addSubview:_emptyLabel];
//    }
//    return _emptyLabel;
//}
//
//- (UIImageView *)emptyImageView
//{
//    if(!_emptyImageView)
//    {
//        UIView *superView = self.view;
//        _emptyImageView = [[UIImageView alloc]init];
//        _emptyImageView.image = [UIImage imageNamed:@"icon_empty"];
//        [superView addSubview:_emptyImageView];
//    }
//    return _emptyImageView;
//}



- (void) masLayoutSubview{
    __weak UIView *superView = self.view;
    
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(superView).with.offset(64);
        make.left.right.equalTo(superView);
        make.bottom.equalTo(superView);
    }];
    
    [self.failView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(superView.mas_top).with.offset(64);
        make.left.right.bottom.mas_equalTo(superView);
    }];
    
    [self.searchView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(superView.mas_top).with.offset(64);
        make.left.right.bottom.mas_equalTo(superView);
    }];
    
    [self.searchView startAnimation];
    

    
//    [self.emptyLabel mas_remakeConstraints:^(MASConstraintMaker *make) {
//        make.centerX.equalTo(superView);
//        make.top.mas_equalTo(self.emptyImageView.mas_bottom).with.offset(px1920Height(164));
//    }];
//    
//    [self.emptyImageView mas_remakeConstraints:^(MASConstraintMaker *make) {
//        make.top.equalTo(superView.mas_top).with.offset(px1920Height(438));
//        make.centerX.equalTo(superView);
//        //        make.width.height.mas_equalTo(px1080Width(400));
//    }];
    
//    self.emptyLabel.hidden = YES;
//    self.emptyImageView.hidden = YES;
    
    
}

@end
